from browser import document
from browser import html
from browser import ajax
from browser import alert
from browser import window
import json

saveGroupInfo = document["saveGroupInfo"]
inputGroupname = document["inputGroupname"]
inputHostsId = document["inputHostsId"]
inputGroupRemask = document["inputGroupRemask"]

fromdata = document.baseURI.split("?")[1]
dataItem = {}
optionChecked = {}

for item in fromdata.split("&"):
    k = item.split("=")[0]
    v = item.split("=")[1]

    dataItem[k] = v


def addUserDatas(req):
    data = json.loads(req.text)
    alert(data)
    window.location.href = "./index.html?page=groups"

def addGroup(ev):
    groupnameVal = inputGroupname.value
    groupRemask = inputGroupRemask.value
    groupHostsVal = ""

    for item in inputHostsId:
        if item.selected:
            if groupHostsVal == "":
                groupHostsVal = str(item.value)
                continue

            groupHostsVal = groupHostsVal + ":" + str(item.value)


    reqData = {}
    reqData["name"] = groupnameVal
    reqData["hostids"] = groupHostsVal
    reqData["remask"] = groupRemask


    request = ajax.Ajax()
    request.bind("complete", addUserDatas)
    request.open("POST", "/manageGroups", False)
    request.send(reqData)

    inputGroupname.value = ""
    inputGroupRemask.value = ""

def updateOptions(req):
    data = json.loads(req.text)
    if data["Code"] == 0:
        for item in  data["Data"]:
            option = html.OPTION(str(item["Id"]) + " "  +item["Addr"] + " "+ item["Remask"])
            option.value = item["Id"]

            if str(item["Id"]) in optionChecked:
                option.selected  = True

            inputHostsId <= option

def queryGroupInfo(req):
    if req.status == 200:
        data = json.loads(req.text)

        if 0 == data["Code"]:
            for checked in (data["Data"][0]["HostsIDs"]).split(":"):
                optionChecked[checked] = True


            request = ajax.Ajax()
            request.bind("complete", updateOptions)
            request.open("GET", "/showHosts", False)
            request.send()

            inputGroupname.value = data["Data"][0]["Names"]
            inputGroupRemask.value = data["Data"][0]["Remask"]

request = ajax.Ajax()
request.bind("complete", queryGroupInfo)
request.open("GET", "/showGroups?groupid="+dataItem["id"], False)
request.send()




saveGroupInfo.bind("click",addGroup)